<template>
    <div class="chat-app">
        <el-container class="container">
            <div class="sidebar-menu">
                <div class="menu-header">
                    <img src="/icons/centerLogo.png" style="width: 80px; cursor: pointer;" @click="jump('/')" />
                </div>
                <div class="menu-content">
                    <img :src="`${BaseUrl}${currentAvatar}`"  @click="jump('/center')"/>
                    <img src="/icons/messageList.png" />
                    <img src="/icons/chat.png" />
                    <img src="/icons/notice.png" />
                    <img src="/icons/setup.png" />
                    <img src="/icons/logout.png" />
                </div>
            </div>
            <el-aside class="user-list">
                <el-input
                    placeholder="搜索用户"
                    prefix-icon="el-icon-search"
                    clearable
                    @input="searchUsers"
                />
                <el-menu class="user-menu">
                    <el-menu-item
                        v-for="user in friendLists"
                        :key="user.id"
                        @click="selectUser(user)"
                        class="user-item"
                        :class="{ active: user.id === selectedUser?.id }"
                    >
                        <div class="user-info">
                            <el-avatar
                                :src="BaseUrl + user.avatar"
                                class="avatar"
                                :class="'avatar-' + user.color"
                            ></el-avatar>
                            <span>{{ user.username }}</span>
                        </div>
                    </el-menu-item>
                </el-menu>
            </el-aside>
            <el-main class="chat-panel">
                <div v-if="selectedUser" class="chat-container">
                    <chat-panel 
                    :user="selectedUser"
                    :messages="currentUserMessages"
                    @send-message="sendMessage"
                    />
                </div>
                <div v-else class="no-user">
                    <p>请选择一个聊天用户</p>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script setup>
import { ref, onMounted,computed } from "vue";
import ChatPanel from "./ChatPanel.vue";
import { getFriendsList, BaseUrl } from "../../../server/userApi";
import { connectWebSocket} from "../../../server/websocket/websocket";
import router from "@/router";
import {useStore} from 'vuex'


const store = useStore()

const friendLists = ref([]);
const selectedUser = computed(()=>{
    console.log(store.state.selectedUserId)
    return  friendLists.value.find(user => user.id === store.state.selectedUserId )
});
// 获取对应的聊天信息
const currentUserMessages = computed(()=>{
    console.log(store.getters.getCurrentUserMessages)
    return store.getters.getCurrentUserMessages
})


const selectUser = (user) => {
    // selectedUser.value = user;
    store.dispatch('selectUser',user.id)
};



const currentAvatar = computed(() => JSON.parse(localStorage.getItem("userInfo")).avatar);

//获取用户的id
const currentUserId = computed(() => JSON.parse(localStorage.getItem("userInfo")).id);

// 接收子组件传递过来的消息
const sendMessage = (message) =>{
    console.log(message)
    store.dispatch('sendMessage',{message,senderId:currentUserId.value})
}


// 连接websokcet
const url = `ws://localhost:8081/imsinglechat?userId=${currentUserId.value}`;
const socket = ref()
onMounted(async () => {
      // 从 localStorage 获取用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    
    // 确保 userInfo 存在且有 id 属性
    if (userInfo && userInfo.id) {
        const userId = userInfo.id;
        
        // 使用获取到的用户 ID 调用 getFriendsList
        const data = await getFriendsList(userId);
        friendLists.value = data.data;
        
        // 如果需要调试，可以取消下面这行的注释
        // console.log(friendLists.value);
        
        socket.value = connectWebSocket(url);
    } else {
        console.error('未找到用户信息或用户ID');
        // 这里可以添加一些错误处理逻辑，比如重定向到登录页面
    }
});


const jump = (path) => {

    router.push(path);
};
</script>

<style lang="scss" scoped>
.chat-app {
    height: 100vh;
    background: rgb(190, 211, 183);
    display: flex;
    justify-content: center;

    .el-container {
        padding: 50px 140px;
    }
    .container {
        width: 100%;
        height: 100%;
        .sidebar-menu {
            width: 70px;
            display: flex;
            flex-direction: column;
            // justify-content: center;
            align-items: center;
            background: #191a1e;
            border-top-left-radius: 10px;
            border-bottom-left-radius: 10px;

            .menu-header {
                margin: 3vh 0 6vh 0;
            }
            .menu-content {
                display: flex;
                flex-direction: column;
                img {
                    margin-bottom: 30px;
                    width: 30px;
                    height: 30px;
                    transition: transform 0.3s ease, border 0.3s ease; /* 添加过渡效果 */
                    border: 2px solid transparent; /* 添加透明边框，防止悬停时的布局移动 */

                    &:hover {
                        transform: scale(1.1);
                        // border: 2px solid #34e89e; /* 使用之前阴影的颜色作为边框色 */
                        cursor: pointer;
                    }
                }
            }
        }

        .user-list {
            color: #fff;
            width: 250px !important;
            background: rgb(42, 43, 42);

            .sidebar-header {
                padding: 20px;
                border-bottom: 1px solid #16213e;
                h3 {
                    font-size: 1.5rem;
                    margin: 0;
                    text-align: center;
                    text-transform: uppercase;
                    letter-spacing: 2px;
                }
            }

            .user-menu {
                background-color: transparent;

                .user-item {
                    display: flex;
                    align-items: center;
                    padding: 15px 20px;
                    color: #e0e0e0;
                    transition: all 0.3s;
                    border-radius: 5px;
                    margin: 5px;

                    &.active,
                    &:hover {
                        background-color: rgba(255, 255, 255, 0.1);
                        color: #fff;
                        transform: translateY(-2px);
                    }

                    .user-info {
                        display: flex;
                        align-items: center;

                        .avatar {
                            margin-right: 15px;
                            transition: all 0.3s;

                            &.avatar-red {
                                --el-avatar-background-color: #ff6b6b;
                            }

                            &.avatar-green {
                                --el-avatar-background-color: #4ecdc4;
                            }

                            &.avatar-blue {
                                --el-avatar-background-color: #45aaf2;
                            }
                        }

                        span {
                            font-weight: 500;
                        }
                    }
                }
            }
        }

        .chat-panel {
            padding: 20px;
            background-color: #fff;

            .chat-container {
                height: 100%;
            }

            .no-user {
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100%;
                color: #7f8c8d;
                font-size: 1.2rem;
                text-align: center;
            }
        }
    }
}
</style>
